using System.Globalization;
using System.Text.RegularExpressions;
using iPhOwa.Exchange.Attributes;
using iPhOwa.Exchange.ContentClasses.Fields;

namespace iPhOwa.Exchange.ContentClasses
{
	/// <summary>
	/// A person (contact) item
	/// </summary>
	[ExchangeContentClass(ContentClassNames.Person)]
	public class Contact : Item
	{
		private string email1;
		private string email2;
		private string email3;

		/// <summary>
		/// Given first name.
		/// </summary>
		[ExchangeField(ContactFields.FirstName)]
		public string FirstName { get; set; }

		/// <summary>
		/// Last name or surname.
		/// </summary>
		[ExchangeField(ContactFields.LastName)]
		public string LastName { get; set; }

		/// <summary>
		/// Company or orgnaization.
		/// </summary>
		[ExchangeField(ContactFields.Organization)]
		public string Company { get; set; }

		/// <summary>
		/// Mobile phone number
		/// </summary>
		[ExchangeField(ContactFields.Mobile)]
		public string MobilePhone { get; set; }

		/// <summary>
		/// Primary email.
		/// </summary>
		[ExchangeField(ContactFields.Email1)]
		public string Email1
		{
			get { return email1; }
			set { email1 = ExtractEmail(value); }
		}

		/// <summary>
		/// Subject line.
		/// </summary>
		public override string Subject
		{
			get { return DisplayName; }
		}

		/// <summary>
		/// Secondary email.
		/// </summary>
		[ExchangeField(ContactFields.Email2)]
		public string Email2
		{
			get { return email2; }
			set { email2 = ExtractEmail(value); }
		}

		/// <summary>
		/// Terciary email.
		/// </summary>
		[ExchangeField(ContactFields.Email3)]
		public string Email3
		{
			get { return email3; }
			set { email3 = ExtractEmail(value); }
		}

		/// <summary>
		/// Work phone number.
		/// </summary>
		[ExchangeField(ContactFields.TelephoneNumber)]
		public string WorkPhone { get; set; }

		/// <summary>
		/// The display name.
		/// </summary>
		public override string DisplayName
		{
			get { return string.Format(CultureInfo.CurrentCulture, "{0} {1}", FirstName, LastName); }
		}

		/// <summary>
		/// Indicates whether this contact is a company or a person.
		/// </summary>
		public bool IsCompany
		{
			get { return string.IsNullOrEmpty(FirstName) && string.IsNullOrEmpty(LastName); }
		}

		/// <summary>
		/// Path to the icon.
		/// </summary>
		public override string IconPath
		{
			get { return "~/Images/icon-contact.gif"; }
		}

		private static string ExtractEmail(string value)
		{
			return value != null ? Regex.Match(value, @"[0-9a-z_+-\.]+@[0-9a-z-\.]+\.[0-9a-z-\.]+").ToString() : string.Empty;
		}
	}
}